package com.price.httplib.ssl

import android.os.Build
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class SSLSocketFactoryCompat : SSLSocketFactory {
    private val delegate: SSLSocketFactory

    //实现X509TrustManager接口
    inner class MyTrustManager : X509TrustManager {
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            return emptyArray()
        }
    }

    constructor() {
        val sc = SSLContext.getInstance("TLS")
        val mMyTrustManager: MyTrustManager = MyTrustManager()
        //        sc.init(null, null, null);
        sc.init(null, arrayOf<TrustManager>(mMyTrustManager), SecureRandom())
        this.delegate = sc.socketFactory
    }

    constructor(delegate: SSLSocketFactory?) {
        if (delegate == null) {
            throw NullPointerException()
        }
        this.delegate = delegate
    }

    override fun getDefaultCipherSuites(): Array<String> {
        return delegate.defaultCipherSuites
    }

    override fun getSupportedCipherSuites(): Array<String> {
        return delegate.supportedCipherSuites
    }

    private fun enableTls12(socket: Socket): Socket {
        if (Build.VERSION.SDK_INT in 16..19) {
            if (socket is SSLSocket) {
                socket.enabledProtocols = TLS_V12_ONLY
            }
        }
        return socket
    }

    @Throws(IOException::class)
    override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
        return enableTls12(delegate.createSocket(s, host, port, autoClose))
    }

    @Throws(IOException::class)
    override fun createSocket(host: String, port: Int): Socket {
        return enableTls12(delegate.createSocket(host, port))
    }

    @Throws(IOException::class)
    override fun createSocket(
        host: String,
        port: Int,
        localHost: InetAddress,
        localPort: Int
    ): Socket {
        return enableTls12(delegate.createSocket(host, port, localHost, localPort))
    }

    @Throws(IOException::class)
    override fun createSocket(host: InetAddress, port: Int): Socket {
        return enableTls12(delegate.createSocket(host, port))
    }

    @Throws(IOException::class)
    override fun createSocket(
        address: InetAddress,
        port: Int,
        localAddress: InetAddress,
        localPort: Int
    ): Socket {
        return enableTls12(delegate.createSocket(address, port, localAddress, localPort))
    }

    companion object {
        private val TLS_V12_ONLY = arrayOf("TLSv1.2")
    }
}
